<template>
  <div class="register-container">
    <div class="register-glow"></div>
    <div class="register-card">
      <div class="register-header">
        <div class="logo-section">
          <div class="logo-icon">🎣</div>
          <h1 class="app-title">FishingWithMe</h1>
          <p class="app-subtitle">创建账户开始钓鱼之旅</p>
        </div>
      </div>

      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-scroll-area">
          <!-- 用户名 -->
          <div class="form-group">
            <label for="username">用户名</label>
            <div class="input-wrapper">
              <input id="username" v-model="form.username" type="text" placeholder="请输入用户名" required :disabled="loading"
                @blur="validateUsername" />
              <span class="input-icon">👤</span>
            </div>
            <span v-if="errors.username" class="error-text">{{ errors.username }}</span>
          </div>

          <!-- 邮箱 -->
          <div class="form-group">
            <label for="email">邮箱</label>
            <div class="input-wrapper">
              <input id="email" v-model="form.email" type="email" placeholder="请输入邮箱地址" required :disabled="loading"
                @blur="validateEmail" />
              <span class="input-icon">📧</span>
            </div>
            <span v-if="errors.email" class="error-text">{{ errors.email }}</span>
          </div>

          <!-- 密码 -->
          <div class="form-group">
            <label for="password">密码</label>
            <div class="input-wrapper">
              <input id="password" v-model="form.password" :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码" required :disabled="loading" @blur="validatePassword" />
              <span class="input-icon">🔒</span>
              <button type="button" class="toggle-password" @click="showPassword = !showPassword">
                {{ showPassword ? '🙈' : '👁️' }}
              </button>
            </div>
            <span v-if="errors.password" class="error-text">{{ errors.password }}</span>
          </div>

          <!-- 确认密码 -->
          <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <div class="input-wrapper">
              <input id="confirmPassword" v-model="form.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'" placeholder="请再次输入密码" required :disabled="loading"
                @blur="validateConfirmPassword" />
              <span class="input-icon">🔒</span>
              <button type="button" class="toggle-password" @click="showConfirmPassword = !showConfirmPassword">
                {{ showConfirmPassword ? '🙈' : '👁️' }}
              </button>
            </div>
            <span v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</span>
          </div>

          <!-- 服务条款 -->
          <div class="form-group checkbox-group">
            <label class="checkbox-label">
              <input v-model="form.agreeTerms" type="checkbox" required :disabled="loading" />
              <span class="checkmark"></span>
              我已阅读并同意
              <a href="#" @click.prevent="showTerms = true">服务条款</a>
              和
              <a href="#" @click.prevent="showPrivacy = true">隐私政策</a>
            </label>
          </div>

          <!-- 注册按钮 -->
          <button type="submit" class="register-btn" :disabled="loading || !isFormValid">
            <span v-if="!loading">立即注册</span>
            <span v-else class="btn-loading">
              <span class="loading-dot"></span>
              <span class="loading-dot"></span>
              <span class="loading-dot"></span>
            </span>
          </button>

          <!-- 登录链接 -->
          <div class="login-link">
            已有账户？
            <a href="#" @click.prevent="$emit('login')">立即登录</a>
          </div>
        </div>
      </form>

      <!-- 错误提示 -->
      <div v-if="error" class="error-toast">
        <div class="error-content">
          <span class="error-icon">⚠️</span>
          {{ error }}
        </div>
      </div>

      <!-- 成功提示 -->
      <div v-if="success" class="success-toast">
        <div class="success-content">
          <span class="success-icon">✅</span>
          {{ success }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue';
import { invoke } from '@tauri-apps/api/core';
import { getCurrentWindow } from '@tauri-apps/api/window';
interface RegisterResponse {
  data?: any;
  msg?: string;
  status: boolean;
  code: number;
}

const emit = defineEmits<{
  login: []
  registerSuccess: [username: string]
}>()

interface FormData {
  username: string
  email: string
  password: string
  confirmPassword: string
  agreeTerms: boolean
}

interface FormErrors {
  username: string
  email: string
  password: string
  confirmPassword: string
}

const form = reactive<FormData>({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  agreeTerms: false
})

const errors = reactive<FormErrors>({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

const loading = ref(false)
const error = ref('')
const success = ref('')
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const showTerms = ref(false)
const showPrivacy = ref(false)
const appWindow = getCurrentWindow();

onMounted(() => {
  appWindow.maximize();
})
// 表单验证
const validateUsername = () => {
  if (!form.username.trim()) {
    errors.username = '用户名不能为空'
  } else if (form.username.length < 3) {
    errors.username = '用户名至少3个字符'
  } else if (!/^[a-zA-Z0-9_]+$/.test(form.username)) {
    errors.username = '用户名只能包含字母、数字和下划线'
  } else {
    errors.username = ''
  }
}

const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!form.email.trim()) {
    errors.email = '邮箱不能为空'
  } else if (!emailRegex.test(form.email)) {
    errors.email = '请输入有效的邮箱地址'
  } else {
    errors.email = ''
  }
}

const validatePassword = () => {
  if (!form.password) {
    errors.password = '密码不能为空'
  } else if (form.password.length < 6) {
    errors.password = '密码至少6个字符'
  } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(form.password)) {
    errors.password = '密码需包含大小写字母和数字'
  } else {
    errors.password = ''
  }
}

const validateConfirmPassword = () => {
  if (form.password !== form.confirmPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
  } else {
    errors.confirmPassword = ''
  }
}

const isFormValid = computed(() => {
  return form.username.trim() &&
    form.email.trim() &&
    form.password &&
    form.confirmPassword &&
    form.password === form.confirmPassword &&
    form.agreeTerms &&
    !errors.username &&
    !errors.email &&
    !errors.password &&
    !errors.confirmPassword
})

const handleRegister = async () => {
  // 验证所有字段
  validateUsername()
  validateEmail()
  validatePassword()
  validateConfirmPassword()

  if (!isFormValid.value) {
    error.value = '请完善表单信息'
    return
  }

  loading.value = true
  error.value = ''
  success.value = ''

  try {
    const response = await invoke<RegisterResponse>('register', {
      userInfo: {
        username: form.username.trim(),
        email: form.email.trim(),
        password: form.password
      }
    })

    if (response.status) {
      success.value = response.msg || '注册成功！正在跳转到登录...'
      setTimeout(() => {
        emit('registerSuccess', form.username)
      }, 1500)
    } else {
      error.value = response.msg || '注册失败'
    }
  } catch (err: any) {
    error.value = err.toString() || '网络错误，请稍后重试'
    console.error('注册错误:', err)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: transparent;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
}

.register-glow {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  height: 600px;
  background: radial-gradient(circle, rgba(29, 185, 84, 0.1) 0%, transparent 70%);
  border-radius: 50%;
  pointer-events: none;
  animation: pulse 4s ease-in-out infinite;
}

@keyframes pulse {

  0%,
  100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.5;
  }

  50% {
    transform: translate(-50%, -50%) scale(1.1);
    opacity: 0.8;
  }
}

.register-card {
  background: rgba(24, 24, 24, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  padding: 30px 40px;
  width: 380px;
  max-width: 90%;
  max-height: 90vh;
  min-height: 500px;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.4);
  position: relative;
  z-index: 10;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.register-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo-icon {
  font-size: 48px;
  margin-bottom: 12px;
  filter: grayscale(1) brightness(2);
}

.app-title {
  color: #ffffff;
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 6px 0;
  letter-spacing: -0.3px;
}

.app-subtitle {
  color: #b3b3b3;
  font-size: 13px;
  margin: 0;
  font-weight: 400;
}

.register-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.form-scroll-area {
  flex: 1;
  overflow-y: auto;
  padding-right: 5px;
  margin-right: -5px;
}

.form-scroll-area::-webkit-scrollbar {
  width: 4px;
}

.form-scroll-area::-webkit-scrollbar-track {
  background: transparent;
}

.form-scroll-area::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
}

.form-scroll-area::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.4);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #ffffff;
  font-size: 14px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper input {
  width: 100%;
  padding: 12px 40px 12px 16px;
  background: rgba(40, 40, 40, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  color: #ffffff;
  font-size: 14px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.input-wrapper input:focus {
  outline: none;
  border-color: #1db954;
  box-shadow: 0 0 0 2px rgba(29, 185, 84, 0.2);
}

.input-wrapper input:disabled {
  background-color: rgba(40, 40, 40, 0.4);
  color: #666;
  cursor: not-allowed;
}

.input-icon {
  position: absolute;
  right: 12px;
  color: #b3b3b3;
  pointer-events: none;
}

.toggle-password {
  position: absolute;
  right: 12px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  color: #b3b3b3;
  transition: color 0.3s ease;
}

.toggle-password:hover {
  color: #1db954;
}

.error-text {
  display: block;
  color: #ff6b6b;
  font-size: 12px;
  margin-top: 5px;
}

.checkbox-group {
  display: flex;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 13px;
  color: #b3b3b3;
}

.checkbox-label input[type="checkbox"] {
  margin-right: 8px;
  accent-color: #1db954;
}

.checkbox-label a {
  color: #1db954;
  text-decoration: none;
}

.checkbox-label a:hover {
  text-decoration: underline;
  color: #1ed760;
}

.register-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #1db954, #1ed760);
  color: #000;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(29, 185, 84, 0.3);
}

.register-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(29, 185, 84, 0.4);
}

.register-btn:disabled {
  background: rgba(40, 40, 40, 0.6);
  color: #666;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 4px;
}

.loading-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: white;
  animation: loading 1.4s infinite ease-in-out both;
}

.loading-dot:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading {

  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

.footer-text {
  text-align: center;
  margin-top: 20px;
  font-size: 13px;
  color: #b3b3b3;
}

.link-primary {
  color: #1db954;
  text-decoration: none;
  font-weight: 600;
  transition: color 0.3s ease;
}

.link-primary:hover {
  text-decoration: none;
  color: #1ed760;
}

.error-toast,
.success-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 8px;
  color: white;
  font-weight: 500;
  z-index: 1000;
  animation: slideIn 0.3s ease;
}

.error-toast {
  background: #e74c3c;
}

.success-toast {
  background: #27ae60;
}

.error-content,
.success-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}
</style>